<?php

abstract class RestResource {

    protected $resourceClass;
    protected $resourcePath;

    protected function __construct($resourceClass, $resourcePath) {
        $this->resourceClass = $resourceClass;
        $this->resourcePath = $resourcePath;
    }

    public function find($id) {
        $b = YougoRestClient::singleton()->get($this->resourcePath . '/' . $id);
        return $this->jsonToObject($b->getResponseText());
    }

    public function findAll() {
        $b = YougoRestClient::singleton()->get($this->resourcePath);
        return $this->jsonToObjectList($b->getResponseText());
    }

    public function findAllAndMap($key, $value) {
        $resources = $this->findAll();

        foreach ($resources as $resource)
            $resourcesMap[$resource->$key] = $resource->$value;

        return $resourcesMap;
    }

    public function create($resource) {
        $b = YougoRestClient::singleton()->post($this->resourcePath, $this->objectToJson($resource));

        // Extracts id from location
        $location = $b->getResponseHeader('Location');
        $id = preg_replace('/.*\/(\d+)/', '\\1', $location);
        return $id;
    }

    public function update($resource) {
        $b = YougoRestClient::singleton()->put($this->resourcePath . '/' . $resource['id'], $this->objectToJson($resource));
    }

    public function delete($id) {
        $b = YougoRestClient::singleton()->delete($this->resourcePath . '/' . $id);
    }

    protected function objectToJson($obj) {
        return json_encode($obj);
    }

    protected function objectToFormUrlEncoded($array) {
        foreach ($array as $key => $value) {
            $formUrlEncoded[] = $key . '=' . $value;
        }
        return implode('&', $formUrlEncoded);
    }

    protected function jsonToObject($json) {
        $resourceArray = json_decode($json);
        $resource = new $this->resourceClass;
        foreach ($resourceArray as $key => $value) {
            $resource->set($key, $value);
        }
        return $resource;
    }

    protected function jsonToObjectList($json) {
        $resourcesArray = json_decode($json);
        $resources = array();
        foreach ($resourcesArray as $resourceArray) {
            $resource = new $this->resourceClass;
            foreach ($resourceArray as $key => $value) {
                $resource->set($key, $value);
            }
            $resources[] = $resource;
        }
        return $resources;
    }

}